package com.chwn.curiousdiary.ui.login;

import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.app.AppCompatActivity;
import android.text.TextUtils;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;

import com.chwn.curiousdiary.DiaryApplication;
import com.chwn.curiousdiary.ui.register.PhoneActivity;
import com.chwn.curiousdiary.ui.main.MainActivity;
import com.chwn.curiousdiary.R;
import com.chwn.curiousdiary.api.IUserApi;
import com.chwn.curiousdiary.api.NetWork;
import com.chwn.curiousdiary.gloable.Constant;
import com.chwn.curiousdiary.gloable.CustomEvent;
import com.chwn.curiousdiary.gloable.User;
import com.chwn.curiousdiary.ui.register.BabySexActivity;
import com.chwn.curiousdiary.utils.CustomToast;
import com.chwn.curiousdiary.utils.DialogUtil;
import com.chwn.harulib.mvp.rx.HttpResult;
import com.chwn.harulib.util.PerfectClickListener;
import com.chwn.harulib.util.RegexValidateUtil;
import com.chwn.harulib.util.ToastUtil;
import com.umeng.analytics.MobclickAgent;
import com.umeng.socialize.UMAuthListener;
import com.umeng.socialize.UMShareAPI;
import com.umeng.socialize.bean.SHARE_MEDIA;

import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import cn.jpush.android.api.JPushInterface;
import de.greenrobot.event.EventBus;
import rx.Observer;
import rx.android.schedulers.AndroidSchedulers;
import rx.functions.Action0;
import rx.schedulers.Schedulers;

/**
 * Description:
 * Copyright  : Copyright (c) 2016
 * Company    :
 * Author     :
 * Date       : 2017/3/25 20:15
 */

public class LoginActivity extends AppCompatActivity {

    @BindView(R.id.et_user_phone)
    EditText mUserPhoneET;
    @BindView(R.id.et_user_pwd)
    EditText mUserPwdET;

    @BindView(R.id.enter_main)
    TextView  mEnterMain;
    @BindView(R.id.iv_login)
    ImageView mLoginIV;

    @BindView(R.id.ib_login_bywx)
    ImageView mLoginBywx;

    private int loginWay = 1;
    private int mEnterWay;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        supportRequestWindowFeature(Window.FEATURE_NO_TITLE);
        getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
                WindowManager.LayoutParams.FLAG_FULLSCREEN);  //全屏
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_login);
        ButterKnife.bind(this);
        initListener();
        mShareAPI = UMShareAPI.get(this);
        mEnterWay = getIntent().getIntExtra(Constant.IS_LOGIN, -1);

        EventBus.getDefault().register(this);
    }

    public void onEventMainThread(CustomEvent event) {
        switch (event.getState()) {
            case CustomEvent.ClOSE_SELF:

                if (event.getPosition() != 5) {
                    finish();
                    if (EventBus.getDefault().isRegistered(this)) {
                        EventBus.getDefault().unregister(this);
                    }
                }
                break;
        }
    }

    protected void initListener() {
        mLoginIV.setOnClickListener(new PerfectClickListener() {
            @Override
            protected void onNoDoubleClick(View v) {
                checkInput();
            }
        });

        mEnterMain.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                EventBus.getDefault().post(new CustomEvent(CustomEvent.FROM_LOOK));
                Intent intent = new Intent(LoginActivity.this, MainActivity.class);
                startActivity(intent);
                finish();
            }
        });

        mLoginBywx.setOnClickListener(new PerfectClickListener() {
            @Override
            protected void onNoDoubleClick(View v) {
                showWaitDialog("跳转中");
                platform = SHARE_MEDIA.WEIXIN;
                mShareAPI.doOauthVerify(LoginActivity.this, platform, umAuthListener);
            }
        });

    }


    private UMShareAPI mShareAPI;
    SHARE_MEDIA platform;

    @OnClick({R.id.fgt_pwd, R.id.tv_register})
    public void onClick(View view) {
        Intent intent;
        switch (view.getId()) {
            case R.id.fgt_pwd: //忘记密码
                intent = new Intent(this, PhoneActivity.class);
                intent.putExtra(Constant.JUMP_TYPE, Constant.FGT_PWD);
                startActivity(intent);
                break;

            case R.id.tv_register: //注册
                intent = new Intent(this, PhoneActivity.class);
                intent.putExtra(Constant.JUMP_TYPE, Constant.REGISTER);
                startActivity(intent);
                break;
        }
    }

    private void checkInput() {
        String phone = mUserPhoneET.getText().toString().trim();
        if (TextUtils.isEmpty(phone)) {
            ToastUtil.shortShowToast("请输入手机号");
            return;
        } else if (!RegexValidateUtil.checkCellphone(phone)) {
            ToastUtil.shortShowToast("请输入正确的手机号");
            return;
        }
        String passWord = mUserPwdET.getText().toString();
        if (TextUtils.isEmpty(passWord)) {
            ToastUtil.shortShowToast("请输入密码");
            return;
        } else if (passWord.length() < Constant.MIN_NUM_PWD || passWord.length() > Constant.MAX_NUM_PWD) {
            ToastUtil.shortShowToast("请输入6-18英文或数字密码");
            return;
        }
        loginWay = 1;
        //        Logger.e(JPushInterface.getRegistrationID(this));
        userLogin(phone, passWord, loginWay, JPushInterface.getRegistrationID(this), null, null, null);
    }

    /**
     * 登录
     */
    private void userLogin(String phone, final String passWord, final int loginWay, String jPushId, final String openId, String nickName, String headUrl) {
        NetWork.getInstance()
                .getApiService(IUserApi.class)
                .userLogin(phone, passWord, loginWay, jPushId, openId, unionid, Constant.OSTYPE, nickName, headUrl)
                .subscribeOn(Schedulers.io())
                .doOnSubscribe(new Action0() {
                    @Override
                    public void call() {
                        showWaitDialog("登录中...");
                    }
                })
                .subscribeOn(AndroidSchedulers.mainThread())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Observer<HttpResult<List<User>>>() {
                    @Override
                    public void onCompleted() {
                        DialogUtil.dismissWaitDialog();
                    }

                    @Override
                    public void onError(Throwable e) {
                        DialogUtil.dismissWaitDialog();
                        errorAction("");
                    }

                    @Override
                    public void onNext(HttpResult<List<User>> userHttpResult) {
                        DialogUtil.dismissWaitDialog();
                        if (userHttpResult.getResult() == Constant.RESULT_ERROR) {
                            errorAction(userHttpResult.getErrorMessage());
                            return;
                        }

                        List<User> resdata = userHttpResult.getResdata();
                        User user = resdata.get(0);
                        user.setPassword(passWord);

                        //登录成功-- 判断是否进行过绑定操作&设置BabyInfo操作
                        if (loginWay == 2 && Integer.parseInt(user.getIsBind()) == 0) {  //微信登录 是否绑定过手机
                            Intent intent = new Intent(LoginActivity.this, PhoneActivity.class);
                            intent.putExtra(Constant.JUMP_TYPE, Constant.BIND_PHONE);
                            intent.putExtra(Constant.UNION_ID, unionid);
                            intent.putExtra(Constant.USER, user);
                            startActivity(intent);

                        } else if (!TextUtils.isEmpty(user.getBabysex())) { //直接进入主页
                            if (mEnterWay == Constant.REQUEST_LOGIN_CODE) {
                                setResult(Constant.REQUEST_LOGIN_CODE);
                            } else {
                                startActivity(new Intent(LoginActivity.this, MainActivity.class));
                            }
                            DiaryApplication.mInstance.saveUser(user);
                            finish();
                        } else { //进入宝宝信息选择页
                            Intent intent = new Intent(LoginActivity.this, BabySexActivity.class);
                            intent.putExtra(Constant.PHONE, user.getPhone());
                            startActivity(intent);
                            DiaryApplication.mInstance.saveUser(user);
                            finish();
                        }

                        /**
                         * 账户统计
                         */
                        MobclickAgent.onProfileSignIn("LoginWay --" + loginWay, "userID -- " + user.getPhone());
                    }
                });
    }

    private void errorAction(String errorMsg) {
        String text;
        if (TextUtils.isEmpty(errorMsg)) {
            text = "请求超时,请检查网络链接";
        } else {
            text = errorMsg;
        }

        CustomToast.showShortToast(text);
    }

    String openId;
    String nickName;
    String headUrl;
    String unionid;


    private UMAuthListener umAuthListener = new UMAuthListener() {
        @Override
        public void onStart(SHARE_MEDIA platform) {

        }

        @Override
        public void onComplete(SHARE_MEDIA platform, int action, Map<String, String> data) {
            if (action == ACTION_AUTHORIZE) {
                switch (platform) {
                    case WEIXIN:
                        openId = data.get("openid");
                        unionid = data.get("unionid");
                        break;
                }

                mShareAPI.getPlatformInfo(LoginActivity.this, platform, umAuthListener);
            }
            if (action == ACTION_GET_PROFILE) {
                switch (platform) {
                    case WEIXIN:
                        openId = data.get("openid");
                        nickName = data.get("screen_name");
                        headUrl = data.get("profile_image_url");
                        unionid = data.get("unionid");
                        break;
                }
                loginWay = 2;
                userLogin(null, null, loginWay, JPushInterface.getRegistrationID(LoginActivity.this), openId, nickName, headUrl);
            }
        }

        @Override
        public void onError(SHARE_MEDIA platform, int action, Throwable t) {
            DialogUtil.dismissWaitDialog();
            ToastUtil.shortShowToast("微信授权失败，请重试");
        }

        @Override
        public void onCancel(SHARE_MEDIA platform, int action) {
            DialogUtil.dismissWaitDialog();
        }
    };


    @Override
    protected void onStop() {
        super.onStop();
        DialogUtil.dismissWaitDialog();
    }


    void showWaitDialog(String text) {
        DialogUtil.showWaitDialog(LoginActivity.this, text, false);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (EventBus.getDefault().isRegistered(this)) {
            EventBus.getDefault().unregister(this);
        }
    }
}
